﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using produccion.clases;
using System.IO;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para frmRepProcProd.xaml
    /// </summary>
    public partial class frmRepProcProd : Window
    {
        CLSENCORDP EncOrd = new CLSENCORDP();
        CLSDETORDP DetOrd = new CLSDETORDP();
        CLSMAEREFP MaeRefp = new CLSMAEREFP();
        CLSMAEREF MaeRef = new CLSMAEREF();
        CLSMAECOL MaeCol = new CLSMAECOL();
        CLSMAECLIP MaeClip = new CLSMAECLIP();
        CLSENCPPCP EncPpcp = new CLSENCPPCP();
        CLSDETPPCP DetPpcp = new CLSDETPPCP();
        CLSMAEPRO MaePro = new CLSMAEPRO();
        CLSENCPRCP EncPrcp = new CLSENCPRCP();
        CLSDETPRCP DetPrcp = new CLSDETPRCP();
        DataTable dtOrd = new DataTable();
        DataTable dtDetalle = new DataTable();
        bool YaEsta = false;
        public frmRepProcProd()
        {
            InitializeComponent();
        }

        private void LimpiarControles()
        {
            txtCodCli.Text = "";
            txtNomCli.Text = "";
            dtpFecha.Text = DateTime.Now.ToShortDateString();
            cbSubCli.Items.Clear();
            txtPedido.Text = "";
            txtCodRef.Text = "";
            txtColor.Text = "";
            dgOrd.ItemsSource = null;
            dtOrd.Clear();
            FormatoDt();
            dgOrd.ItemsSource = dtOrd.DefaultView;
            btnGrabar.IsEnabled = true;
            YaEsta = false;
            dgOrd.IsReadOnly = false;
            btnGrabar.IsEnabled = true;
            txtOperario.Text = "";
            dtpFechaRep.Text = DateTime.Today.ToShortDateString();
            imgFoto.Source = null;
            txtNomRef.Text = "";
        }

        private void FormatoDt()
        {
            dtOrd.Rows.Clear();
            dtOrd.Columns.Clear();
            dtOrd.Clear();
            dtOrd.Columns.Add(new DataColumn("Seccion-Pedido", System.Type.GetType("System.String")));
            DataRow dr = dtOrd.NewRow();
            dr[0] = "Orden";
            dtOrd.Rows.Add(dr);
            dr = dtOrd.NewRow();
            dr[0] = "Programación";
            dtOrd.Rows.Add(dr);
            dr = dtOrd.NewRow();
            dr[0] = "Corte";
            dtOrd.Rows.Add(dr);
            dr = dtOrd.NewRow();
            dr[0] = "Preparación";
            dtOrd.Rows.Add(dr);
            dr = dtOrd.NewRow();
            dr[0] = "Guarnecida";
            dtOrd.Rows.Add(dr);
            dr = dtOrd.NewRow();
            dr[0] = "Montaje";
            dtOrd.Rows.Add(dr);
            dr = dtOrd.NewRow();
            dr[0] = "Despachos";
            dtOrd.Rows.Add(dr);
            dgOrd.CanUserAddRows = false;
            dgOrd.CanUserDeleteRows = false;
        }

        private void btnSalir_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void txtOrden_TextChanged(object sender, TextChangedEventArgs e)
        {
            LimpiarControles();
        }

        private void txtOrden_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F2)
            {

            }

            if (e.Key == Key.Return)
            {
                if (txtOrden.Text == "") return;
                FormatoDt();
                EncOrd.NROORD_EOP = txtOrden.Text;
                if (EncOrd.existe())
                {
                    YaEsta = true;
                    EncOrd.consultar();
                    dtpFecha.Text = EncOrd.FECORD_EOP.ToShortDateString();
                    txtCodCli.Text = EncOrd.CODCLI_EOP;
                    MaeClip.CODCLI_CLI = txtCodCli.Text;
                    MaeClip.consultar();
                    txtNomCli.Text = MaeClip.NOMCLI_CLI;
                    txtPedido.Text = EncOrd.NROPED_EOP.ToString();
                    txtCodRef.Text = EncOrd.CODREF_EOP;
                    MaeRef.CODREF_REF = txtCodRef.Text;
                    MaeRef.Consultar();
                    txtNomRef.Text = MaeRef.NOMREF_REF.Trim();
                    BitmapImage b = new BitmapImage();
                    if (File.Exists(MDOgeneral.Fotos_BOSI + MaeRef.CODREF_REF + ".jpg"))
                    {
                        b.BeginInit();
                        b.UriSource = new Uri(MDOgeneral.Fotos_BOSI + MaeRef.CODREF_REF + ".jpg");
                        b.EndInit();
                        imgFoto.Stretch = Stretch.Fill;
                        imgFoto.Source = b;
                    }
                    else
                    {
                        imgFoto.Source = null;
                    }
                    MaeCol.CODCOL_COL = EncOrd.CODCOL_EOP;
                    MaeCol.Consultar();
                    txtColor.Text = "";
                    txtColor.Text = MaeCol.CODCOL_COL + "-" + MaeCol.NOMCOL_COL.Trim();
                    MaePro.CODREF_PRO = txtCodRef.Text;
                    MaePro.CODCOL_PRO = txtColor.Text.Substring(0, 2);
                    DataTable dt = MaePro.BuscarTallas();
                    for (int j = 1; j < dt.Rows.Count; j++)
                    {
                        dtOrd.Columns.Add(new DataColumn(dt.Rows[j - 1][0].ToString(), System.Type.GetType("System.Double")));
                    }
                    DetOrd.NROORD_DOP = txtOrden.Text;
                    DetOrd.CODREF_DOP = txtCodRef.Text;
                    DetOrd.CODCOL_DOP = txtColor.Text.Substring(0, 2);
                    dgOrd.ItemsSource = null;
                    dgOrd.ItemsSource = dtOrd.DefaultView;
                    EncPrcp.NROORD_EPP = txtOrden.Text;
                    dtDetalle = EncPrcp.consCatPro();
                    for (int j = 1; j < dtOrd.Columns.Count; j++)
                    {
                        DetOrd.CODTAL_DOP = dtOrd.Columns[j].Caption;
                        if (DetOrd.existe())
                        {
                            DetOrd.consultar();
                            dtOrd.Rows[0][j] = (DetOrd.CANORD_DOP);
                            dtOrd.Rows[1][j] = DetOrd.CANPRG_DOP;
                            dtOrd.Rows[2][j] = DetOrd.CANCOR_DOP;
                            dtOrd.Rows[3][j] = DetOrd.CANPRP_DOP;
                            dtOrd.Rows[4][j] = DetOrd.CANGUA_DOP;
                            dtOrd.Rows[5][j] = DetOrd.CANMON_DOP;
                            dtOrd.Rows[6][j] = DetOrd.CANDES_DOP;
                        }
                        else
                        {
                            dtOrd.Rows[0][j] = 0;
                        }
                    }
                    dgOrd.ItemsSource = null;
                    dgOrd.ItemsSource = dtOrd.DefaultView;
                    bool Encontro = false;
                    for (int i = 1; i < dtOrd.Rows.Count; i++)
                    {
                        Encontro = false;
                        for (int j = 1; j < dtOrd.Columns.Count; j++)
                        {
                            if (dtOrd.Rows[i][j].ToString() != "" && System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()) > 0 && (System.Convert.ToDouble(dtOrd.Rows[i][j].ToString())==System.Convert.ToDouble(dtOrd.Rows[0][j].ToString())))
                            {
                                Encontro = true;
                            }
                        }
                        if (Encontro == false)
                        {
                            tbEstado.Text = dtOrd.Rows[i][0].ToString();
                            return;
                        }
                    }
                    tbEstado.Text = "Completa";
                    btnGrabar.IsEnabled = false;
                }
            }
        }

        private void dgOrd_KeyDown(object sender, KeyEventArgs e)
        {
            int i = dgOrd.SelectedIndex;
            if (i == -1) return;
            if (dgOrd.CurrentCell.Column == null) return;
            int j = dgOrd.CurrentCell.Column.DisplayIndex;
            if (j == 0) dgOrd.IsReadOnly = true;
            if (dtOrd.Rows[0][j].ToString() == "")

                if (i > 3)
                    dgOrd.IsReadOnly = false;
                else
                    dgOrd.IsReadOnly = true;
        }

        private void dgOrd_LostFocus(object sender, RoutedEventArgs e)
        {
            int i = dgOrd.SelectedIndex;
            if (i == -1) return;
            if (dgOrd.CurrentCell.Column == null) return;
            int j = dgOrd.CurrentCell.Column.DisplayIndex;
            if (j == 0) return;
            if (i > 3)
                dgOrd.IsReadOnly = false;
            else
                dgOrd.IsReadOnly = true;
            if (dtOrd.Rows[i][j].ToString() == "") dtOrd.Rows[i][j] = 0;
            if (dtOrd.Rows[0][j].ToString() == "") return;
            if (System.Convert.ToDouble(dtOrd.Rows[0][j].ToString()) < System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()))
            {
                MessageBox.Show("La cantidad de la orden es menor que la cantidad ingresada!", "Órdenes", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                if (i == 0) dtOrd.Rows[i][j] = DetOrd.CantidadOrdenada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                if (i == 1) dtOrd.Rows[i][j] = DetOrd.CantidadProgramada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                if (i == 2) dtOrd.Rows[i][j] = DetOrd.CantidadCortada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                if (i == 3) dtOrd.Rows[i][j] = DetOrd.CantidadPreparada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                if (i == 4) dtOrd.Rows[i][j] = DetOrd.CantidadGuarnecida(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                if (i == 5) dtOrd.Rows[i][j] = DetOrd.CantidadMontaje(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                if (i == 6) dtOrd.Rows[i][j] = DetOrd.CantidadDespachada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption);
                return;
            }
        }

        private void dgOrd_GotFocus(object sender, RoutedEventArgs e)
        {
            int i = dgOrd.SelectedIndex;
            if (i == -1) return;
            if (i > 3)
                dgOrd.IsReadOnly = false;
            else
                dgOrd.IsReadOnly = true;
        }

        private void btnGrabar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (tbEstado.Text == "Completa")
                {
                    MessageBox.Show("La orden ya está completa", "Órdenes", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
                if (txtOperario.Text == "")
                {
                    MessageBox.Show("Ingrese un código de operario", "Órdenes", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }

                if (dtpFechaRep.Text == "")
                {
                    MessageBox.Show("Ingrese una fecha de reporte", "Órdenes", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
                int i = 0;
                for (int j = 1; j < dtOrd.Columns.Count; j++)
                {
                    if (dtOrd.Rows[1][j].ToString() != "")
                    {
                        if (System.Convert.ToDouble(dtOrd.Rows[1][j].ToString()) == DetOrd.CantidadProgramada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption))
                        {
                            i = 1;
                        }
                    }
                    if (dtOrd.Rows[2][j].ToString() != "")
                    {
                        if (System.Convert.ToDouble(dtOrd.Rows[2][j].ToString()) == DetOrd.CantidadCortada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption))
                        {
                            i = 2;
                        }
                    }
                    if (dtOrd.Rows[3][j].ToString() != "")
                    {
                        if (System.Convert.ToDouble(dtOrd.Rows[3][j].ToString()) == DetOrd.CantidadPreparada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption))
                        {
                            i = 3;
                        }
                    }
                    if (dtOrd.Rows[4][j].ToString() != "")
                    {
                        if (System.Convert.ToDouble(dtOrd.Rows[4][j].ToString()) == DetOrd.CantidadGuarnecida(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption))
                        {
                            i = 4;
                        }
                    }
                    if (dtOrd.Rows[5][j].ToString() != "")
                    {
                        if (System.Convert.ToDouble(dtOrd.Rows[5][j].ToString()) == DetOrd.CantidadMontaje(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption))
                        {
                            i = 5;
                        }
                    }
                    if (dtOrd.Rows[6][j].ToString() != "")
                    {
                        if (System.Convert.ToDouble(dtOrd.Rows[6][j].ToString()) == DetOrd.CantidadDespachada(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption))
                        {
                            i = 6;
                        }
                    }
                }

                MDOgeneral.transaccion = MDOgeneral.conexion.BeginTransaction();
                int Consecutivo = DetPrcp.Consecutivo(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2));
                for (int j = 1; j < dtOrd.Columns.Count; j++)
                {
                    if (dtOrd.Rows[i][j].ToString() != "")
                    {
                        if (i == 1) DetOrd.ActCanPrg(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()));
                        if (i == 1) DetPrcp.Insertar(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()), "PRG", Consecutivo);
                        if (i == 2) DetOrd.ActCanCor(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()));
                        if (i == 2) DetPrcp.Insertar(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()), "COR", Consecutivo);
                        if (i == 3) DetOrd.ActCanPrp(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()));
                        if (i == 3) DetPrcp.Insertar(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()), "PRP", Consecutivo);
                        if (i == 4) DetOrd.ActCanGua(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()));
                        if (i == 4) DetPrcp.Insertar(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()), "GUA", Consecutivo);
                        if (i == 5) DetOrd.ActCanMon(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()));
                        if (i == 5) DetPrcp.Insertar(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()), "MON", Consecutivo);
                        if (i == 6) DetOrd.ActCanDes(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()));
                        if (i == 6) DetPrcp.Insertar(txtOrden.Text, txtCodRef.Text, txtColor.Text.Substring(0, 2), dtOrd.Columns[j].Caption, System.Convert.ToDouble(dtOrd.Rows[i][j].ToString()), "DES", Consecutivo);
                    }
                }
                string PRC = "";
                if (i == 1) PRC = "PRG";
                if (i == 2) PRC = "COR";
                if (i == 3) PRC = "PRP";
                if (i == 4) PRC = "GUA";
                if (i == 5) PRC = "MON";
                if (i == 6) PRC = "DES";
                if (i > 0)
                {
                    EncPrcp.Insertar(txtOrden.Text, PRC, Consecutivo, dtpFechaRep.Text, txtOperario.Text);
                    MessageBox.Show("Información actualizada!", "Órdenes", MessageBoxButton.OK, MessageBoxImage.Hand);
                }
                LimpiarControles();
            }
            catch (Exception ex)
            {
                MDOgeneral.transaccion.Rollback();
                MessageBox.Show("Error al grabar procesos: " + ex.Message, "Órdenes", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnOperario_Click(object sender, RoutedEventArgs e)
        {
            CLSMAEEMPP Emp = new CLSMAEEMPP();
            FRMbuscar f = new FRMbuscar(new clases.CLSMAEEMPP(), "buscar", "Nombre", "NOMEMP_EMP", "Codigo");
            f.ShowDialog();

            if (f.retorno != "" && !txtOperario.Text.Equals(f.retorno))
            {
                txtOperario.Text = f.retorno;

            }
        }

        private void txtOperario_TextChanged(object sender, TextChangedEventArgs e)
        {
            
        }

        private void txtOperario_LostFocus(object sender, RoutedEventArgs e)
        {
            CLSMAEEMPP Emp = new CLSMAEEMPP();
            Emp.CODEMP_EMP = txtOperario.Text;
            if (!Emp.existe())
                txtOperario.Text = "";
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(txtOrden);
        }

        private void dgOrd_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        }        
    }    
}
